package cn.jbolt.common.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.json.JFinalJson;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.log.Log;
import cn.jbolt.common.model.RoleProducts;
import cn.jbolt.common.vo.FileAttach;
import cn.jbolt.common.vo.LandInfoVo;
import cn.jbolt.common.vo.MsgVo;
import cn.jbolt.common.vo.TddjVo;

public class LreaService {

	private Log LOG = Log.get(LreaService.class);

	/**
	 * private Archivesinfo archivesinfoDao = new Archivesinfo().dao(); private
	 * AttachProducts attachProductsDao = new AttachProducts().dao(); private
	 * FileCatalog fileCatalogDao = new FileCatalog().dao(); private FilesIdx
	 * filesIdxDao = new FilesIdx().dao(); private Fileslist fileslistDao = new
	 * Fileslist().dao(); private InfoProducts InfoProductsDao = new
	 * InfoProducts().dao();
	 **/
	private RoleProducts roleProductsDao = new RoleProducts().dao();

	public MsgVo findLandReg(LandInfoVo landInfo) {
		MsgVo msg = new MsgVo();
		StringBuilder from = new StringBuilder("from v_tddj_tddjda where 1=? ");
		DbPro dbPro = new DbPro("oralce9i");
		List<Object> params = new ArrayList<>();
		params.add("1");
		if (landInfo.getLandCode() != null) {
			from.append(" AND CERTIFACATRION=?");
			params.add(landInfo.getLandCode());
		}
		if (landInfo.getTownCode() != null) {
			from.append(" AND EREA=?");
			params.add(landInfo.getTownCode());
		}
		if (landInfo.getObligee() != null) {
			from.append(" AND OWNER=?");
			params.add(landInfo.getObligee());
		}
		if (landInfo.getRegCode() != null) {
			from.append(" AND FILEBARCODE=?");
			params.add(landInfo.getRegCode());
		}
		if (landInfo.getRegDateStart() != null) {
			from.append(" AND TO_char(S_DATE,'yyyy-mm-dd')>=?");
			params.add(landInfo.getRegDateStart());
		}
		if (landInfo.getRegDateEnd() != null) {
			from.append(" AND TO_char(S_DATE,'yyyy-mm-dd')<=?");
			params.add(landInfo.getRegDateEnd());
		}

		String totalRowSql = "select count(*) " + from.toString();
		String findSql = "select * " + from.toString();
		LOG.info(findSql.toString());
		Page<Record> page = dbPro.paginateByFullSql(landInfo.getPageNumber(), landInfo.getPageSize(), totalRowSql, findSql, params.toArray());
		List<Record> l = page.getList();
		Page<TddjVo> pageTddj = new Page<TddjVo>();
		BeanUtil.copyProperties(page, pageTddj, new String[] { "list" });
		pageTddj.setList(new ArrayList<TddjVo>());
		for (Record record : l) {
			Map<String, Object> map = record.getColumns();
			TddjVo tddj = JsonKit.parse(JFinalJson.getJson().toJson(map), TddjVo.class);
			pageTddj.getList().add(tddj);
		}
		msg.setData(pageTddj);
		return msg;
	}

	public MsgVo findEa(String fileBarcode) {
		MsgVo msg = new MsgVo();
		List<FileAttach> fileList = new ArrayList<FileAttach>();
		String sql = "select * from v_file_attch_products where bar_code=? order by f_pname";
		List<Record> records = Db.find(sql, fileBarcode);
		if (records.isEmpty()) {
			DbPro dbPro = new DbPro("mssql");
			records = dbPro.find(sql, fileBarcode);
		}
		for (Record record : records) {
			Map<String, Object> map = record.getColumns();
			FileAttach fileAttach = JsonKit.parse(JFinalJson.getJson().toJson(map), FileAttach.class);
			fileList.add(fileAttach);
		}
		msg.setData(fileList);
		return msg;
	}

	public MsgVo findFile(FileAttach fileAttach) {
		MsgVo msg = new MsgVo();
		String sql = "select * from v_file_attch_products where bar_code=? and serialid=?";
		Object[] params = new Object[] { fileAttach.getBar_code(), fileAttach.getSerialid() };
		Record record = null;
		if (1 == fileAttach.getType()) {
			record = Db.findFirst(sql, params);
		} else if (2 == fileAttach.getType()) {
			DbPro dbPro = new DbPro("mssql");
			record = dbPro.findFirst(sql, params);
		}
		Map<String, String> fileMap = new HashMap<>();
		String fileBase64 = null;
		if (record != null) {
			Prop p = PropKit.use(String.format("ftp%d.properties", fileAttach.getType()));
			String filePath = record.getStr("file_path");
			if (filePath.indexOf(":") > 0) {
				filePath = filePath.substring(filePath.indexOf(":") + 1).replaceAll("\\\\", "/");
				filePath = "%s".concat(filePath.substring(filePath.indexOf("C") - 1));
				fileBase64 = getFileByFtp(p, String.format(filePath, "/F"));
				if (fileBase64 == null)
					fileBase64 = getFileByFtp(p, String.format(filePath, "/G"));
				if (fileBase64 == null)
					fileBase64 = getFileByFtp(p, String.format(filePath, "/E"));
				if (fileBase64 == null)
					fileBase64 = getFileByFtp(p, String.format(filePath, "/F1"));

			} else {
				fileBase64 = getFileByFtp(p, filePath);
			}
			/*
			 * try { FileReader fileReader = new FileReader(record.getStr("file_path"));
			 * fileBase64 = Base64.encode(fileReader.readBytes()); } catch (Exception e) {
			 * LOG.error("路径错误" + record.getStr("file_path"), e);
			 * msg.setMsg("电子档案文件路径存在问题，未能获取"); msg.setSuccess(false); return msg; }
			 */
			if (fileBase64 == null) {
				LOG.error("路径错误" + record.getStr("file_path"));
				msg.setMsg("电子档案文件路径存在问题，未能获取");
				msg.setSuccess(false);
				return msg;
			}
			fileMap.put("fileName", record.getStr("f_pname"));
			fileMap.put("fileBase64", fileBase64);
			msg.setData(fileMap);
		} else {
			msg.setMsg("未找到对应文件");
			msg.setSuccess(false);
		}

		return msg;

	}

	private String getFileByFtp(Prop p, String filePath) {
		ByteArrayOutputStream bout = null;
		Ftp ftp = null;
		try {

			bout = new ByteArrayOutputStream();
			ftp = new Ftp(p.get("ftp_ip"), p.getInt("ftp_port"), p.get("ftp_user"), p.get("ftp_pwd"));
			// 进入远程目录
			String path = filePath.substring(0, filePath.lastIndexOf("/"));
			String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
			if (ftp.cd(path)) {
				// 下载远程文件
				ftp.download(path, fileName, bout);
				String str = Base64.encode(bout.toByteArray());
				bout.close();
				ftp.close();
				return str;
			}else {
				LOG.error("路径错误："+ filePath);
			}
		} catch (IOException e) {
			LOG.error(e);
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		return null;
	}

	public Page<RoleProducts> paginate(LandInfoVo landInfo, int pageNumber, int pageSize) {
		LOG.info("YYYYYYYYYYYYYYYYY");
		List<Object> params = new ArrayList<>();
		StringBuffer sql = new StringBuffer("FROM FILE_ROLE_PRODUCTS WHERE 1=1  ");
		if (landInfo.getLandCode() != null) {
			sql.append(" AND LAND_CODE=?");
			params.add(landInfo.getLandCode());
		}
		if (landInfo.getTownCode() != null) {
			sql.append(" AND TOWN_VILLAGE_CODE=?");
			params.add(landInfo.getTownCode());
		}
		if (landInfo.getObligee() != null) {
			sql.append(" AND OBLIGEE=?");
			params.add(landInfo.getObligee());
		}
		if (landInfo.getRegCode() != null) {
			sql.append(" AND OLD_A_CODE=?");
			params.add(landInfo.getRegCode());
		}
		if (landInfo.getRegDateStart() != null) {
			sql.append(" AND REG_DATE>=?");
			params.add(landInfo.getRegDateStart());
		}
		if (landInfo.getRegDateEnd() != null) {
			sql.append(" AND REG_DATE<=?");
			params.add(landInfo.getRegDateEnd());
		}
		sql.append(" order by SERIALID asc");
		return roleProductsDao.paginate(pageNumber, pageSize, "select * ", sql.toString(), params.toArray());
	}

	public static void main(String[] args) {
		String filePath = "F:\\dggtFilesShare\\图处件\\已上传\\C00038468-33\\005.jpg";
		System.out.println(filePath.substring(filePath.indexOf(":") + 1));
		System.out.println(filePath.substring(0, filePath.indexOf(":")));
		filePath = filePath.substring(filePath.indexOf(":") + 1).replaceAll("\\\\", "/");
		System.out.println(filePath.substring(filePath.indexOf("C") - 1));
	}

}
